package com.example.mybank.tool;

import lombok.Data;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

@Data
public class JsonResult<T>  implements Serializable {
    Integer code;
    String message;
    Date time;
    Long timestamp;
    T data;

    public JsonResult(){
        setBase();
        code=0;
        message="成功";
        this.data=null;
    }

    public JsonResult(T data){
        setBase();
        code=0;
        message="成功";
        this.data=data;
    }

    public JsonResult(ResultCode resultCode){
        setBase();
        code= resultCode.getCode();
        message= resultCode.getMessage();
        this.data=null;
    }

    public JsonResult(ResultCode resultCode, Exception exception){
        setBase();
        code= resultCode.getCode();
        message= resultCode.getMessage()+":"+exception.getClass()+": "+exception.getMessage();
        this.data=null;
    }


    private void setBase(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        time = new Date();
        message=df.format(time);
        timestamp= time.getTime();
    }

    public static JsonResult failWithCode(ResultCode resultCode){
        return new JsonResult(resultCode);
    }

    public static JsonResult fail(Exception exception){
        if(exception instanceof MyException){
            return failWithCode(((MyException)(exception)).resultCode);
        }else{
            return new JsonResult(ResultCode.UNKNOWN_EXCEPTION,exception);
        }
    }

    public static JsonResult ok(Object data){
        return new JsonResult(data);
    }



}
